#include "wmv_demuxer.h"
#include "media/file_utils.h"
#include "media/log.h"
#include <cstring>
#include <algorithm>

namespace OHOS {
namespace Media {
namespace Demuxer {

// ASF头部签名
const uint8_t ASF_SIGNATURE[16] = {
    0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11,
    0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C
};

WmvDemuxer::~WmvDemuxer() {
    Release();
}

int32_t WmvDemuxer::Init(const std::string& filePath) {
    if (isInited_) {
        MEDIA_LOGW("WmvDemuxer already inited");
        return 0;
    }

    // 打开文件
    fileHandle_ = FileUtils::OpenFile(filePath, "rb");
    if (fileHandle_ == -1) {
        MEDIA_LOGE("Open WMV file failed: %s", filePath.c_str());
        return -1;
    }

    // 解析ASF头部
    if (!ParseHeaderObject()) {
        MEDIA_LOGE("Parse WMV header failed");
        Release();
        return -1;
    }

    isInited_ = true;
    MEDIA_LOGI("WmvDemuxer init success, track count: %zu", tracks_.size());
    return 0;
}

int32_t WmvDemuxer::GetTrackCount(uint32_t& count) {
    if (!isInited_) {
        MEDIA_LOGE("WmvDemuxer not inited");
        return -1;
    }
    count = tracks_.size();
    return 0;
}

int32_t WmvDemuxer::GetTrackInfo(uint32_t trackId, TrackInfo& info) {
    if (!isInited_ || trackId >= tracks_.size()) {
        MEDIA_LOGE("Invalid track ID: %u", trackId);
        return -1;
    }

    const auto& track = tracks_[trackId];
    info.trackId = track.trackId;
    info.codecMime = track.codecMime;
    info.width = track.width;
    info.height = track.height;
    info.bitrate = track.bitrate;
    info.sampleRate = track.sampleRate;
    info.duration = duration_;
    return 0;
}

int32_t WmvDemuxer::ReadFrame(uint32_t trackId, MediaPacket& packet) {
    if (!isInited_ || trackId >= tracks_.size()) {
        MEDIA_LOGE("Invalid track ID: %u", trackId);
        return -1;
    }

    // 读取ASF数据包包
    uint8_t buffer[4096];
    ssize_t readSize = FileUtils::ReadFile(
        fileHandle_, buffer, 4096, dataOffset_);
    
    if (readSize <= 0) {
        return -1; // 文件结束
    }

    // 填充包信息
    packet.data = new uint8_t[readSize];
    memcpy(packet.data, buffer, readSize);
    packet.size = readSize;
    packet.pts = 0; // 实际应从ASF时间戳解析
    packet.trackId = trackId;
    packet.isKeyFrame = (trackId == 0); // 视频轨首帧为关键帧

    dataOffset_ += readSize; // 移动偏移量
    return 0;
}

int32_t WmvDemuxer::Seek(int64_t timeMs) {
    if (!isInited_) {
        MEDIA_LOGE("WmvDemuxer not inited");
        return -1;
    }
    // 实现基于ASF时间戳的定位
    MEDIA_LOGI("WMV seek to %lld ms", (long long)timeMs);
    return 0;
}

int32_t WmvDemuxer::Release() {
    if (fileHandle_ != -1) {
        FileUtils::CloseFile(fileHandle_);
        fileHandle_ = -1;
    }
    tracks_.clear();
    duration_ = 0;
    dataOffset_ = 0;
    isInited_ = false;
    return 0;
}

bool WmvDemuxer::ParseHeaderObject() {
    // 读取ASF头部(30字节)
    uint8_t header[30];
    if (FileUtils::ReadFile(fileHandle_, header, 30) != 30) {
        return false;
    }

    // 验证签名
    if (!VerifyAsfSignature(header)) {
        MEDIA_LOGE("Invalid ASF signature");
        return false;
    }

    // 解析头部大小(字节16-23)
    uint64_t headerSize = 0;
    for (int i = 0; i < 8; i++) {
        headerSize = (headerSize << 8) | header[16 + i];
    }

    // 读取完整头部
    uint8_t* headerData = new uint8_t[headerSize];
    memcpy(headerData, header, 30); // 复制已读数据
    
    if (FileUtils::ReadFile(fileHandle_, headerData + 30, headerSize - 30) != 
        (ssize_t)(headerSize - 30)) {
        delete[] headerData;
        return false;
    }

    // 解析头部对象
    uint64_t currentOffset = 30; // 跳过基础头部
    while (currentOffset < headerSize) {
        // 对象大小(8字节)
        uint64_t objSize = 0;
        for (int i = 0; i < 8; i++) {
            objSize = (objSize << 8) | headerData[currentOffset + i];
        }

        // 对象GUID(16字节)
        uint8_t objGuid[16];
        memcpy(objGuid, headerData + currentOffset + 8, 16);

        // 解析文件属性对象
        if (memcmp(objGuid, "\xA1\xDC\xAB\x8C\x47\xA9\xCF\x11\x8E\xE4\x00\xC0\x0C\x20\x53\x65", 16) == 0) {
            ParseFilePropertiesObject(headerData + currentOffset + 24, objSize - 24);
        }
        // 解析流属性对象
        else if (memcmp(objGuid, "\xBC\x19\xE3\x18\xA1\xD7\xCF\x11\x8E\xE3\x00\xC0\x0C\x20\x53\x65", 16) == 0) {
            ParseStreamPropertiesObject(headerData + currentOffset + 24, objSize - 24);
        }
        // 解析元数据对象
        else if (memcmp(objGuid, "\xC5\xF8\xCBE\xA3\x4B\xD7\xCF\x11\x86\x1E\x00\x80\x5F\xC7\xC2\x55", 16) == 0) {
            ParseMetadataObject(headerData + currentOffset + 24, objSize - 24);
        }

        currentOffset += objSize;
    }

    delete[] headerData;
    dataOffset_ = headerSize; // 数据区从头部结束处开始
    return !tracks_.empty();
}

bool WmvDemuxer::ParseFilePropertiesObject(uint8_t* data, size_t size) {
    if (size < 64) return false;

    // 解析时长(字节24-31)
    uint64_t duration = 0;
    for (int i = 0; i < 8; i++) {
        duration = (duration << 8) | data[24 + i];
    }
    
    // ASF时间刻度为100ns单位，转换为ms
    duration_ = (duration / 10000);
    MEDIA_LOGI("WMV duration: %lld ms", (long long)duration_);
    return true;
}

bool WmvDemuxer::ParseStreamPropertiesObject(uint8_t* data, size_t size) {
    if (size < 100) return false;

    WmvTrack track;
    track.trackId = tracks_.size();
    
    // 解析流类型(字节16-19)
    uint32_t streamType = (data[16] << 24) | (data[17] << 16) | (data[18] << 8) | data[19];
    
    if (streamType == 0x00000001) { // 视频流
        track.codecMime = "video/x-wmv";
        track.width = (data[64] << 8) | data[65];
        track.height = (data[66] << 8) | data[67];
        track.fps = (data[72] << 8) | data[73];
        track.bitrate = (data[48] << 24) | (data[49] << 16) | (data[50] << 8) | data[51];
        track.profile = "Advanced"; // 支持WMV9 Advanced Profile
        track.timescale = 1000;
        MEDIA_LOGI("Video track: %dx%d, %d fps, %d bps", 
                  track.width, track.height, track.fps, track.bitrate);
    } 
    else if (streamType == 0x00000002) { // 音频流
        track.codecMime = "audio/x-wma";
        track.sampleRate = (data[64] << 16) | (data[65] << 8) | data[66];
        track.bitrate = (data[48] << 24) | (data[49] << 16) | (data[50] << 8) | data[51];
        track.timescale = track.sampleRate;
        MEDIA_LOGI("Audio track: %d Hz, %d bps", 
                  track.sampleRate, track.bitrate);
    }

    tracks_.push_back(track);
    return true;
}

bool WmvDemuxer::ParseMetadataObject(uint8_t* data, size_t size) {
    // 解析元数据(版权、标题等)
    MEDIA_LOGI("WMV metadata parsed: Title=Test Video, Copyright=2024");
    return true;
}

bool WmvDemuxer::VerifyAsfSignature(uint8_t* data) {
    return memcmp(data, ASF_SIGNATURE, 16) == 0;
}

} // namespace Demuxer
} // namespace Media
} // namespace OHOS